#include "TestHttp.h"

#include <QJsonObject>
#include <qjsondocument.h>

void TestHttp::OnReplyFinished(QNetworkReply* reply)
{
    if (QNetworkReply::NoError == reply->error())
    {
        auto _data = reply->readAll();
        ui.plainTextEdit->appendPlainText(_data);
    }
}

TestHttp::TestHttp(QWidget *parent)
    : QMainWindow(parent)
    , m_manager{}
{
    ui.setupUi(this);
    OnInitDialog();
    
}

void TestHttp::OnInitDialog()
{
    if (nullptr == m_manager)
    {
        m_manager = new QNetworkAccessManager(this);
        Q_ASSERT(m_manager);
        connect(m_manager, &QNetworkAccessManager::finished, this, &TestHttp::OnReplyFinished);
    }
}

void TestHttp::on_pushButton_send_clicked()
{
    QJsonObject _object{};
#if 0
    _object.insert("loginName", "operation1");
    _object.insert("machineCode", "operation1");
    _object.insert("password", "123456");
#endif // 0

    _object.insert("loginName",QJsonValue(ui.lineEdit_name->text()));
    _object.insert("machineCode",QJsonValue(ui.lineEdit_machine->text()));
    _object.insert("password", QJsonValue(ui.lineEdit_password->text()));

    QJsonDocument _doc{};
    _doc.setObject(_object);
    QByteArray _array = _doc.toJson(QJsonDocument::Compact);

    QNetworkRequest _request{};
    _request.setUrl(QUrl("http://124.70.67.72/login"));
    _request.setRawHeader("Content-Type", "application/json");
    if (m_manager)
    {
        m_manager->post(_request, _array);
    }

}
